
redis.log(redis.LOG_NOTICE, "brand query start... ");
--分页函数
local getPageIndex = function(x)
    local page = {}
    local startIndex=ARGV[1]
    local endIndex=ARGV[1]+ARGV[2]-1
    if KEYS[3]=="ASC" then
        startIndex=-ARGV[1]-ARGV[2]
        endIndex=-ARGV[1]-1
    end
    redis.log(redis.LOG_NOTICE, " query  brand start:"..startIndex.." end:"..endIndex);
    table.insert(page,startIndex)
    table.insert(page,endIndex)
    return page
end
local not_empty = function(x)
    return (type(x) == "table") and (not x.err) and (#x ~= 0)
end
--字符串分割函数
--传入字符串和分隔符，返回分割后的table
function string.split(str, delimiter,prefix)
    local result = {}
    if str==nil or str=='' or delimiter==nil then
        return nil
    end
    string.gsub(str, '[^'..delimiter..']+', function(w) table.insert(result, prefix..w) end )
    --计算最分值大值参数
    table.insert(result, "AGGREGATE")
    table.insert(result,"MAX")
    return result
end
local tempProductList ="temp:brand_id:"
local all_id
local total
local list2={}

local values=string.split(ARGV[3],",",KEYS[4])
local size_t = table.getn(values)
local temp_key="temp_key"
local tempStyle="temp:style"
if #ARGV==4 then
    --查询品牌风格
    local values_style=string.split(ARGV[4],",",KEYS[5])
    local values_style_size = table.getn(values_style)
    redis.call("ZUNIONSTORE",tempStyle,values_style_size-2,unpack(values_style))
end
if size_t==3 then
    if #ARGV==3 then
        redis.call("ZINTERSTORE", tempProductList,2,values[1],KEYS[2],"AGGREGATE","MAX")
    elseif #ARGV==4 then
        redis.call("ZINTERSTORE", tempProductList,3,tempStyle,values[1],KEYS[2],"AGGREGATE","MAX")
        redis.call("DEL", tempStyle)
    end
else
    redis.call("ZUNIONSTORE", temp_key,size_t-2,unpack(values))
    if #ARGV==3 then
        redis.call("ZINTERSTORE", tempProductList,2,temp_key,KEYS[2],"AGGREGATE","MAX")
    elseif #ARGV==4 then
        redis.call("ZINTERSTORE", tempProductList,3,tempStyle,temp_key,KEYS[2],"AGGREGATE","MAX")
    end
    redis.call("DEL", temp_key)
    redis.call("DEL", tempStyle)
end
total=redis.call("ZCARD", tempProductList);
local page= getPageIndex(total)
all_id =redis.call("ZREVRANGE", tempProductList,page[1],page[2]);

--获取brand对象
if not_empty(all_id) then
    local i=1
    while(i<=#all_id) do
        local brand=redis.call("GET",KEYS[1]..all_id[i]);
        if brand~=nil then
            if KEYS[3]=="ASC" then
                table.insert(list2,1,brand);
            else
                table.insert(list2,brand);
            end
        end
        i=i+1
    end
end
redis.call("DEL", tempProductList)

redis.log(redis.LOG_NOTICE, "brand query finish! total :"..total);
return {total,list2}

